<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;

class UserController extends BaseController
{
    public function index()
    {
        $data = array('list' => array(['time' => 2024, 'info' => ['name' => '是的', 'age' => 16]])
        );

        $data = array(['time' => 2024, 'info' => ['name' => '是的', 'age' => 16]]
        );

        return $data;
    }

    private function commonCurl($url)
    {
        $username = 'admin';
        $password = 'Gjxqgwh@2023!';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 禁用SSL证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);
        return $response;
    }

    /**
     * @return bool|string rangeDay
     * $json = {
     *     code:1,
     *      msg:null,
     *      data:{
     *          all_total_bytes:12324324235,
     *          items:[
     *              {
     *                  name:10.23.231.2,
     *                  total_bytes:10.224.32.88,
     *                  up_bytes:12.3232,
     *                  down_bytes:323232324,
     *                  total_bytes:59617459
     *              }
     *          ]
     *      }
     * }
     * 互联网用户流量排名  用户流量概览
     */
    public function rangeDay()
    {
        $url = 'https://10.224.29.9/api/v3/Objects/MonitorUser/range/day';
        $data = $this->commonCurl($url);
        if ($data) {
            $res = json_decode(deepCopy($data));
            $list = $res->data->items;
            foreach ($list as $key => $value) {
                $mbNumber = bytesToMB($value->down_bytes);
                $rounded = number_format($mbNumber, 2); // 保留两位小数
                $value->down_bytes = $rounded;

                $mbNumber = bytesToMB($value->up_bytes);
                $rounded = number_format($mbNumber, 2); // 保留两位小数
                $value->up_bytes = $rounded;

                $mbNumber = bytesToMB($value->total_bytes);
                $rounded = number_format($mbNumber, 2); // 保留两位小数
                $value->total_bytes = $rounded;
            }

        }
        return json_encode($res);
    }
}
